<template>
	<el-card>
		<el-row style="margin-bottom: 10px">
			<a-col :span="24">
				<!-- 纸张设置 -->
				<el-button-group style="margin:0 0px">
					<el-button v-for="(value,type) in paperTypes" :type="curPaperType === type ? 'primary' : ' '"
						@click="setPaper(type,value)" :key="type">
						{{ type }}
					</el-button>
				</el-button-group>
				<el-input-number style="margin:0 0px" :value="scaleValue " :precision="2" :step="0.1" :min="scaleMin"
					:max="scaleMax" @change="changeScale"></el-input-number>
				<el-popover placement="bottom" width="300" title="设置纸张宽高(mm)" v-model="paperPopVisible">
					<div style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 10px">
						<el-input type="number" v-model="paperWidth" style=" width: 100px; text-align: center"
							place="宽（mm）"></el-input>~
						<el-input type="number" v-model="paperHeight" style=" width: 100px; text-align: center"
							place="高（mm）"></el-input>
					</div>
					<div>
						<el-button type="primary" style="width: 100%" @click="otherPaper" size="mini">确定</el-button>
					</div>
					<el-button slot="reference" type="primary" style="margin:0 10px">自定义宽高</el-button>
				</el-popover>


				<!-- 预览/打印 -->
				<el-button-group>
					<el-row>
						<el-button type="primary" icon="el-icon-view" @click="preView">
							预览
						</el-button>

						<el-button type="primary" icon="el-icon-s-management" @click="save">
							保存
						</el-button>
						<el-button type="danger" icon="el-icon-delete" @click="clearPaper">
							清空
						</el-button>
						<!-- <el-button size="small" icon="el-icon-plus" @click="addPanel(editableTabsValue)"></el-button> -->
						<el-button size="small" icon="el-icon-plus" @click="addPanel(editableTabsValue)"></el-button>
					</el-row>

				</el-button-group>
				<div class="tag">
					<!-- 因为你这里v-model， 点击的时候editableTabsValue自动变了 -->
					<el-tabs v-model="editableTabsValue" type="card" closable 
						@tab-click="tabClick" @tab-remove="removeTab">
						<el-tab-pane v-for="(item, index) in editableTabs" :key="item.name" :label="item.title"
							:name="item.name">
						</el-tab-pane>
					</el-tabs>
				</div>

				<!-- 保存/清空 -->
			</a-col>
		</el-row>
		<a-row>
			<a-col :span="4">
				<a-card style="height: 100vh">
					<a-row>
						<a-col :span="24" class="rect-printElement-types hiprintEpContainer">
						</a-col>
					</a-row>
				</a-card>
			</a-col>
			<a-col :span="14">
				<a-card class="card-design">
					<div id="hiprint-printTemplate" class="hiprint-printTemplate"></div>
				</a-card>
			</a-col>
			<a-col :span="6" class="params_setting_container">
				<a-card>
					<a-row class="hinnn-layout-sider">
						<div id="PrintElementOptionSetting"></div>
					</a-row>
				</a-card>
			</a-col>
		</a-row>
		<!-- 预览 -->
		<print-preview ref="preView" />
	</el-card>
</template>

<script>
	import printPreview from './preview'
	import {
		MessageBox
	} from 'element-ui'
	import {
		hiprint
	} from 'vue-plugin-hiprint'
	import providers from './providers'
	import printData from './print-data'
	import defPanel from './defPanel'

	let hiprintTemplate;
	export default {
		name: "sales",
		components: {
			printPreview
		},
		data() {
			return {
				paperPopVisible: false,
				// 模板选择
				mode: 0,

				// 当前纸张
				curPaper: {
					type: 'other',
					width: 210,
					height: 296.6
				},
				// 纸张类型
				paperTypes: {
					'A3': {
						width: 420,
						height: 296.6
					},
					'A4': {
						width: 210,
						height: 296.6
					},
					'A5': {
						width: 210,
						height: 147.6
					},
					'B3': {
						width: 500,
						height: 352.6
					},
					'B4': {
						width: 250,
						height: 352.6
					},
					'B5': {
						width: 250,
						height: 175.6
					}
				},
				scaleValue: 1,
				scaleMax: 5,
				scaleMin: 0.5,
				// 自定义纸张
				paperPopVisible: false,
				paperWidth: '210',
				paperHeight: '296.6',
				editableTabsValue: '1', //选中第1个标签页
				lastEditableTabsValue: '1',
				editableTabs: [{
					title: '模板 1',
					name: '1',
					json: {
						"panels": [{
							"index": 0,
							"paperType": "A4",
							"height": 297,
							"width": 210,
							"paperHeader": 45,
							"paperFooter": 802.5,
							"printElements": [{
								"options": {
									"left": 250.5,
									"top": 24,
									"height": 9.75,
									"width": 120,
									"title": "模板1",
									"fontFamily": "SimSun",
									"fontSize": 16.5,
									"fontWeight": "bold",
									"letterSpacing": 3,
									"color": "#0a0909",
									"textAlign": "center"
								},
								"printElementType": {
									"type": "text"
								}
							}]
						}]
					},
				} ],
				tabIndex: 1,
			}
		},
		computed: {
			curPaperType() {
				let type = 'other'
				let types = this.paperTypes
				for (const key in types) {
					let item = types[key]
					let {
						width,
						height
					} = this.curPaper
					if (item.width === width && item.height === height) {
						type = key
					}
				}
				return type
			}
		},
		mounted() {
			this.init()
			this.otherPaper()
		},

		methods: {
			init() {
				let {
					mode
				} = this
				let provider = providers[mode]
				hiprint.init({
					providers: [provider.f]
				});
				$('.hiprintEpContainer').empty()
				hiprint.PrintElementTypeManager.build('.hiprintEpContainer', provider.value);
				$('#hiprint-printTemplate').empty()
				// let templates = this.$ls.get('KEY_TEMPLATES', {})
				// let template = templates[provider.value] ? templates[provider.value] : {},				
				hiprintTemplate = new hiprint.PrintTemplate({
					template: this.editableTabs[0].json,
					settingContainer: '#PrintElementOptionSetting',
					paginationContainer: '.hiprint-printPagination'
				});
				hiprintTemplate.design('#hiprint-printTemplate');
				console.log("打印面板", hiprintTemplate);
				console.log("打印当前数组数据1", this.editableTabs);
				// 获取当前放大比例, 当zoom时传true 才会有
				this.scaleValue = hiprintTemplate.editingPanel.scale || 1;
			},
			//增加模板
			addPanel(targetName) {
				let that = this;
				let lastTabIdx = this.editableTabs.findIndex(item => item.name == that.lastEditableTabsValue);  //true
				if (lastTabIdx > -1) {
					let lastTab = this.editableTabs[lastTabIdx];
					lastTab.json = hiprintTemplate.getJson();
					this.editableTabs.splice(lastTabIdx, 1, lastTab)
				}
				let newTabName = ++this.editableTabsValue+ '';
				console.log("当前模板数",newTabName);
				// 自定义默认模板json
				let template = defPanel;
				// 看效果
				template.panels[0].printElements[0].options.title = "模板" + newTabName;
				// 清空dom节点
				$('#hiprint-printTemplate').empty()
				hiprintTemplate = new hiprint.PrintTemplate({
					template: template,
					settingContainer: '#PrintElementOptionSetting',
					paginationContainer: '.hiprint-printPagination'
				});
				console.log("当前模板", hiprintTemplate);
				hiprintTemplate.design('#hiprint-printTemplate');


				this.editableTabs.push({
					title: '模板' + newTabName,
					name: newTabName, //标识符
					json: template
				});
				this.editableTabsValue = newTabName;
				this.lastEditableTabsValue = newTabName;
				console.log("lastEditableTabsValue",this.lastEditableTabsValue);
				console.log("打印当前数组数据", this.editableTabs);
			},
			//点击切换模板
			tabClick(e) {
				let that = this;
				// 保存上一个模板的json
				let lastTabIdx = this.editableTabs.findIndex(e => e.name == that.lastEditableTabsValue);  //true
				if (lastTabIdx > -1) {
					let lastTab = this.editableTabs[lastTabIdx];
					lastTab.json = hiprintTemplate.getJson();
					this.editableTabs.splice(lastTabIdx, 1, lastTab)
				}
		
				// 获取到当前点击tab,更新当前tab的json
				let index = parseInt(e.index)   //解析字符串，返回整数
				let tab = this.editableTabs[index];
				$('#hiprint-printTemplate').empty()
				hiprintTemplate = new hiprint.PrintTemplate({
					template: tab.json,
					settingContainer: '#PrintElementOptionSetting',
					paginationContainer: '.hiprint-printPagination'
				});
				hiprintTemplate.design('#hiprint-printTemplate');
				that.lastEditableTabsValue = that.editableTabsValue;
			},
			
			//删除标签
			removeTab(targetName) {
				console.log("target",targetName);
				let tabs = this.editableTabs;
				let activeName = this.editableTabsValue; //4
				console.log("当前下标",activeName);
				if (activeName === targetName) {
					tabs.forEach((tab, index) => {
						if (tab.name === targetName) { //true
							let nextTab = tabs[index + 1] || tabs[index - 1]; //false  ||  true
							if (nextTab) {
								console.log("nextTab", nextTab);
								activeName = nextTab.name;
							}
						}
					});
				}
				this.editableTabsValue = activeName;
				let index = tabs.findIndex(e => e.name == activeName);  //true
				console.log("index",index);
				$('#hiprint-printTemplate').empty()
				hiprintTemplate = new hiprint.PrintTemplate({
					template: tabs[index].json,
					settingContainer: '#PrintElementOptionSetting',
					paginationContainer: '.hiprint-printPagination'
				});
				hiprintTemplate.design('#hiprint-printTemplate');
				this.editableTabs = tabs.filter(tab => tab.name !== targetName);
				this.lastEditableTabsValue = this.editableTabsValue
			},



			/**
			 * 设置纸张大小
			 * @param type [A3, A4, A5, B3, B4, B5, other]
			 * @param value {width,height} mm
			 */
			setPaper(type, value) {
				try {
					if (Object.keys(this.paperTypes).includes(type)) {
						this.curPaper = {
							type: type,
							width: value.width,
							height: value.height
						}
						hiprintTemplate.setPaper(value.width, value.height)
					} else {
						this.curPaper = {
							type: 'other',
							width: value.width,
							height: value.height
						}
						hiprintTemplate.setPaper(value.width, value.height)
					}
				} catch (error) {
					this.$message.error(`操作失败: ${error}`)
				}
			},
			changeScale(currentValue, oldValue) {
				let big = false
				currentValue <= oldValue ? big = false : big = true
				let scaleValue = this.scaleValue;
				if (big) {
					scaleValue += 0.1;
					if (scaleValue > this.scaleMax) scaleValue = 5;
				} else {
					scaleValue -= 0.1;
					if (scaleValue < this.scaleMin) scaleValue = 0.5;
				}
				if (hiprintTemplate) {
					// scaleValue: 放大缩小值, false: 不保存(不传也一样), 如果传 true, 打印时也会放大
					hiprintTemplate.zoom(scaleValue);
					this.scaleValue = scaleValue;
				}
			},
			clearPaper() {
				MessageBox.confirm('是否确认清空模板信息?', '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					try {
						hiprintTemplate.clear();
					} catch (error) {
						this.$message.error(`操作失败: ${error}`);
					}
				}).catch((err) => {
					console.log(err)
				})
			},
			otherPaper() {
				let value = {}
				value.width = this.paperWidth
				value.height = this.paperHeight
				this.paperPopVisible = false
				this.setPaper('other', value)
			},
			preView() {
				let {
					width
				} = this.curPaper
				this.$refs.preView.show(hiprintTemplate, printData, width)
			},

			save() {
				let {
					mode
				} = this
				let provider = providers[mode]
				this.setTemplate({
					name: provider.value,
					json: hiprintTemplate.getJson()
				})
			},
			setTemplate(payload) {
				let templates = this.$ls.get('KEY_TEMPLATES', {})
				console.log("打印当前data", payload.json)
				templates[payload.name] = payload.json
				this.$ls.set('KEY_TEMPLATES', templates)
				this.$message.info('保存成功')
			}
		}
	}
</script>

<style lang="less" scoped>
	// build 拖拽
	/deep/ .hiprint-printElement-type>li>ul>li>a {
		padding: 4px 4px;
		color: #1296db;
		line-height: 1;
		height: auto;
		text-overflow: ellipsis;
	}

	// 设计容器
	.card-design {
		overflow: hidden;
		overflow-x: auto;
		overflow-y: auto;
	}

</style>
